package top.revery.task.service;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import top.revery.api.entity.user.BaseCompanyUser;
import top.revery.task.dto.CompanyDto;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package 企业
 * @date 2019/12/13 9:26
 */
@Service
public class CompanyService {
    @Autowired
    private CompanyDto companyDto;

    @GlobalTransactional
    public Page<BaseCompanyUser> findPage(int pageNum, int pageSize, Map map) {

        Specification<BaseCompanyUser> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        return companyDto.findAll(specification, pageRequest);
    }

    private Specification<BaseCompanyUser> createSpecification(Map map) {
        return new Specification<BaseCompanyUser>() {
            @Override
            public Predicate toPredicate(Root<BaseCompanyUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //id
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    predicate.getExpressions().add(cb.equal(root.get("id"), map.get("id")));
                }
                //省
                if (map.get("provincesId") != null && !"".equals(map.get("provincesId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("provincesId"), map.get("provincesId")));
                }
                //市
                if (map.get("citiesId") != null && !"".equals(map.get("citiesId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("citiesId"), map.get("citiesId")));
                }

                if (map.get("status") != null && !"".equals(map.get("status"))) {
                    predicate.getExpressions().add(cb.equal(root.get("status"), map.get("userType")));
                }
                return predicate;
            }
        };
    }
}
